import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
// 进度条插件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [

    {
      path: '/login',
      component: () => import('@/views/Login/index.vue')
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      // 重定向, 如果进来没有指定子路由, 默认转向首页
      redirect: 'home',

      children: [
        {
          path: 'home',
          component: () => import('@/views/Home/index.vue'),
          meta: {
            title: '首页'
          }
        },
        {
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
          meta: {
            title: '健康百科'
          }
        },
        {
          path: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: {
            title: '消息中心'
          }
        },
        {
          path: 'user',
          component: () => import('@/views/User/index.vue'),
          meta: {
            title: '我的'
          }
        },
        {
          path: '/user/patient',
          component: () => import('@/views/User/PatientPage.vue'),
          meta: { title: '家庭档案' }
        },
      ]
    }

  ]
})
NProgress.configure({
  showSpinner: false
})
// 页面关闭之前 和关闭之后都是要进度条控制
// 这里的from, next 没有就不要写 不然会报错
// router.beforeEach((to, from, next) => {
router.beforeEach((to) => {
  NProgress.done()
  document.title = `忧医问诊${to.meta.title}`
  const store = useUserStore()
  const whileList = ['/login']
  if (!store.user?.token && !whileList.includes(to.path)) {
    return '/login'
  }
})
router.afterEach((to) => {
  NProgress.done()
  document.title = `忧医问诊${to.meta.title}`
})

export default router
